package com.zt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zt.annotation.AdminLog;
import com.zt.dto.TeacherDto;
import com.zt.entity.Result;
import com.zt.entity.TeacherCertification;
import com.zt.entity.Teachers;
import com.zt.enums.TeacherCertificationStatus;
import com.zt.vo.TeacherReviewVO;
import com.zt.service.TeacherCertificationService;
import com.zt.service.TeachersService;
import com.zt.service.FileUploadService;
import io.minio.MinioClient;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.Date;

/*
 * 教师管理控制器
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private TeachersService teacherService;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private TeacherCertificationService teacherCertificationService;

    private static String AVATAR_IMAGE;

    /**
     * 分页查询教师列表
     */
    @PostMapping("/list")
    public Result list(@RequestBody TeacherDto teacherDto) {
        // 假设前端传递 pageNum、pageSize 字段
        IPage<Teachers> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                teacherDto.getPageNum(), teacherDto.getPageSize());
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();
        if (teacherDto.getName() != null && !teacherDto.getName().isEmpty()) {
            queryWrapper.like("name", teacherDto.getName());
        }
        if (teacherDto.getStatus() != null && !teacherDto.getStatus().isEmpty()) {
            queryWrapper.eq("status", teacherDto.getStatus());
        }

        List<Teachers> records = teacherService.page(page, queryWrapper).getRecords();
        for (Teachers teachers : records) {
            Integer teachersId = teachers.getId();
            // 根据教师id 查询教师认证表中的内容
            QueryWrapper<TeacherCertification> teacherCertificationQueryWrapper = new QueryWrapper<>();
            teacherCertificationQueryWrapper.eq("teacher_id", teachersId);
            TeacherCertification certificationByid = teacherCertificationService.getOne(teacherCertificationQueryWrapper);
            teachers.setTeacherCertification(certificationByid);
        }

        System.out.println("获取纯记录"+records);
        return Result.success("查询成功", page);
    }

    /**
     * 切换教师状态
     */
    @PutMapping("/{id}/toggle-status")
    public Result toggleTeacherStatus(@PathVariable("id") Integer id) {
        try {
            if (id == null || id <= 0) {
                return Result.error("教师ID无效");
            }
            Teachers teacher = teacherService.getById(id);
            if (teacher == null) {
                return Result.error("教师不存在");
            }
            int newStatus = teacher.getStatus() != null && teacher.getStatus() == 1 ? 0 : 1;
            teacher.setStatus(newStatus);
            boolean updated = teacherService.updateById(teacher);
            if (!updated) {
                return Result.error("更新教师状态失败");
            }
            String statusText = newStatus == 1 ? "在职" : "离职";
            Map<String, Object> response = new HashMap<>();
            response.put("id", teacher.getId());
            response.put("status", newStatus);
            response.put("message", "教师状态更新成功：" + statusText);
            return Result.success("操作成功", response);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("服务器内部错误，请重试");
        }
    }

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 上传教师头像
     */
    @PostMapping("/upload")
    public Result uploadAvatar(MultipartFile file) {
        try {
            String imageUrl = fileUploadService.uploadTeacherAvatar(file);
            AVATAR_IMAGE = imageUrl; // 保存到静态变量供后续使用
            return Result.success("上传成功", imageUrl);
        } catch (Exception e) {
            return Result.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 新增教师
     */
    @PostMapping("/add")
    public Result add(@RequestBody TeacherDto teacherDto) {
        /*    private String name;
    private String status;

    private String avatar;

    private String email;

    private String introduction; // 简介

    private String phone;

    private String title; // 职称

    private String subject; //专业*/
        Teachers teachers = new Teachers();
        teachers.setName(teacherDto.getName());
        teachers.setStatus(Integer.parseInt(teacherDto.getStatus()));
        teachers.setAvatar(teacherDto.getAvatar());
        teachers.setEmail(teacherDto.getEmail());
        teachers.setIntroduction(teacherDto.getIntroduction());
        teachers.setPhone(teacherDto.getPhone());
        teachers.setTitle(teacherDto.getTitle());
        teachers.setSubjectIds(teacherDto.getSubject());

        // todo 设置用户id
        teachers.setUserId(ThreadLocalRandom.current().nextInt());  // todo 这里是死数据，需要和后端关联起来


        teachers.setCertificationStatus(1); // 默认待认证
        teachers.setCreatedAt(new Date()); // 如果有创建时间字段可加
        boolean result = teacherService.save(teachers);
        if (result) {
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }

    /**
     * 更新教师信息
     */
    @PutMapping("/{id}")
    public Result updateTeacher(@RequestBody Teachers teacher) {
        // teacher.setUpdatedAt(new Date()); // 如果有更新时间字段可加
        boolean update = teacherService.updateById(teacher);
        if (update) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    /**
     * 批量删除教师
     */
    @DeleteMapping("{ids}")
    public Result batchDeleteTeacher(@PathVariable("ids") String ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要删除的教师");
        }
        try {
            List<Integer> idList = Arrays.stream(ids.split(","))
                    .map(Integer::parseInt)
                    .toList();
            boolean result = teacherService.removeByIds(idList);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("服务器异常，请重试");
        }
    }

    /**
     * 获取教师下拉选项
     */
    @GetMapping("/options")
    public Result getTeacherOptions() {
        return Result.success("获取老师选项成功", teacherService.list());
    }

    /**
     * 获取教师审核统计数据
     */
    @GetMapping("/review/stats")
    public Result getTeacherReviewStats() {
        try {
            // 查询所有教师的认证状态统计
            QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();

            // 总数
            Long total = teacherService.count();

            // 待认证数量
            queryWrapper.clear();
            queryWrapper.eq("certification_status", 1);
            Long pending = teacherService.count(queryWrapper);

            // 已认证数量
            queryWrapper.clear();
            queryWrapper.eq("certification_status", 2);
            Long approved = teacherService.count(queryWrapper);

            // 未通过数量
            queryWrapper.clear();
            queryWrapper.eq("certification_status", 3);
            Long rejected = teacherService.count(queryWrapper);

            // 构建统计结果
            Map<String, Object> stats = new HashMap<>();
            stats.put("total", total);
            stats.put("pending", pending);
            stats.put("approved", approved);
            stats.put("rejected", rejected);

            return Result.success("获取教师审核统计成功", stats);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取教师审核统计失败：" + e.getMessage());
        }
    }

    /**
     * 获取教师审核列表
     */
    @GetMapping("/review/list")
    public Result getTeacherReviewList(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "status", required = false) String status) {

        try {
            // 创建分页对象
            IPage<Teachers> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);

            // 构建查询条件
            QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();

            // 根据教师姓名模糊查询
            if (name != null && !name.trim().isEmpty()) {
                queryWrapper.like("name", name.trim());
            }

            // 根据认证状态查询
            if (status != null && !status.trim().isEmpty()) {
                queryWrapper.eq("certification_status", status);
            }

            // 按创建时间倒序排列
            queryWrapper.orderByDesc("created_at");

            // 执行分页查询
            IPage<Teachers> teacherPage = teacherService.page(page, queryWrapper);
            List<Teachers> records = teacherPage.getRecords();

            // 转换为VO对象并补充认证信息
            List<TeacherReviewVO> reviewList = new ArrayList<>();
            for (Teachers teacher : records) {
                // 查询教师认证信息
                QueryWrapper<TeacherCertification> certWrapper = new QueryWrapper<>();
                certWrapper.eq("teacher_id", teacher.getId());
                TeacherCertification certification = teacherCertificationService.getOne(certWrapper);

                // 转换为VO对象
                TeacherReviewVO reviewVO = convertToReviewVO(teacher, certification);
                reviewList.add(reviewVO);
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", reviewList);
            result.put("total", teacherPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取教师审核列表成功", result);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取教师审核列表失败：" + e.getMessage());
        }
    }

    /**
     * 审核通过教师
     */
    @PutMapping("/review/{id}/approve")
    @AdminLog(module = "教师管理", operation = "审核通过", description = "审核通过教师认证申请", type = AdminLog.OperationType.UPDATE)
    public Result approveTeacher(@PathVariable("id") Integer teacherId) {
        try {
            // 1. 查询教师信息
            Teachers teacher = teacherService.getById(teacherId);
            if (teacher == null) {
                return Result.error("教师不存在");
            }

            // 2. 更新教师认证状态为已认证
            teacher.setCertificationStatus(2); // 2-已认证
            boolean updateTeacherResult = teacherService.updateById(teacher);

            if (!updateTeacherResult) {
                return Result.error("更新教师认证状态失败");
            }

            // 3. 更新教师认证表状态
            QueryWrapper<TeacherCertification> certWrapper = new QueryWrapper<>();
            certWrapper.eq("teacher_id", teacherId);
            TeacherCertification certification = teacherCertificationService.getOne(certWrapper);

            if (certification != null) {
                certification.setStatus(1); // 1-已通过
                certification.setUpdateTime(new Date());
                teacherCertificationService.updateById(certification);
            }

            return Result.success("教师审核通过成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("审核操作失败：" + e.getMessage());
        }
    }

    /**
     * 审核拒绝教师
     */
    @PutMapping("/review/{id}/reject")
    @AdminLog(module = "教师管理", operation = "审核拒绝", description = "审核拒绝教师认证申请", type = AdminLog.OperationType.UPDATE)
    public Result rejectTeacher(@PathVariable("id") Integer teacherId, @RequestBody Map<String, String> params) {
        try {
            String reason = params.get("reason");
            if (reason == null || reason.trim().isEmpty()) {
                return Result.error("请填写拒绝原因");
            }

            // 1. 查询教师信息
            Teachers teacher = teacherService.getById(teacherId);
            if (teacher == null) {
                return Result.error("教师不存在");
            }

            // 2. 更新教师认证状态为未通过
            teacher.setCertificationStatus(3); // 3-未通过
            boolean updateTeacherResult = teacherService.updateById(teacher);

            if (!updateTeacherResult) {
                return Result.error("更新教师认证状态失败");
            }

            // 3. 更新教师认证表状态和拒绝原因
            QueryWrapper<TeacherCertification> certWrapper = new QueryWrapper<>();
            certWrapper.eq("teacher_id", teacherId);
            TeacherCertification certification = teacherCertificationService.getOne(certWrapper);

            if (certification != null) {
                certification.setStatus(2); // 2-已驳回
                certification.setRejectReason(reason.trim());
                certification.setUpdateTime(new Date());
                teacherCertificationService.updateById(certification);
            }

            return Result.success("教师审核拒绝成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("审核操作失败：" + e.getMessage());
        }
    }

    /**
     * 获取教师审核详情
     */
    @GetMapping("/review/{id}/detail")
    public Result getTeacherReviewDetail(@PathVariable("id") Integer teacherId) {
        try {
            // 1. 查询教师基本信息
            Teachers teacher = teacherService.getById(teacherId);
            if (teacher == null) {
                return Result.error("教师不存在");
            }

            // 2. 查询教师认证信息
            QueryWrapper<TeacherCertification> certWrapper = new QueryWrapper<>();
            certWrapper.eq("teacher_id", teacherId);
            TeacherCertification certification = teacherCertificationService.getOne(certWrapper);
            teacher.setTeacherCertification(certification);

            return Result.success("获取教师审核详情成功", teacher);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取教师审核详情失败：" + e.getMessage());
        }
    }

    /**
     * 将Teachers和TeacherCertification转换为TeacherReviewVO
     */
    private TeacherReviewVO convertToReviewVO(Teachers teacher, TeacherCertification certification) {
        TeacherReviewVO vo = new TeacherReviewVO();

        // 设置教师基本信息
        vo.setId(teacher.getId());
        vo.setName(teacher.getName());
        vo.setIntroduction(teacher.getIntroduction());
        vo.setTeachingAge(teacher.getTeachingAge());
        vo.setCertificationStatus(teacher.getCertificationStatus());
        vo.setCertificationStatusText(TeacherCertificationStatus.getDescriptionByCode(teacher.getCertificationStatus()));
        vo.setApplyTime(teacher.getCreatedAt());

        // 设置认证信息
        if (certification != null) {
            vo.setPhone(certification.getPhone());
            vo.setEmail(certification.getEmail());
            vo.setEducation(certification.getEducation());
            vo.setGraduateSchool(certification.getGraduateSchool());
            vo.setMajor(certification.getMajor());
            vo.setIdNumber(certification.getIdNumber());
            vo.setIdCardFront(certification.getIdCardFront());
            vo.setIdCardBack(certification.getIdCardBack());
            vo.setDiplomaImg(certification.getDiplomaImg());
            vo.setTeacherCertImg(certification.getTeacherCertImg());
            vo.setRejectReason(certification.getRejectReason());

            // 构建证书图片列表
            List<String> certificates = new ArrayList<>();
            if (certification.getIdCardFront() != null && !certification.getIdCardFront().isEmpty()) {
                certificates.add(certification.getIdCardFront());
            }
            if (certification.getIdCardBack() != null && !certification.getIdCardBack().isEmpty()) {
                certificates.add(certification.getIdCardBack());
            }
            if (certification.getDiplomaImg() != null && !certification.getDiplomaImg().isEmpty()) {
                certificates.add(certification.getDiplomaImg());
            }
            if (certification.getTeacherCertImg() != null && !certification.getTeacherCertImg().isEmpty()) {
                certificates.add(certification.getTeacherCertImg());
            }
            vo.setCertificates(certificates);
        }

        return vo;
    }

    /**
     * 导出教师审核数据为Excel
     */
    @GetMapping("/review/export")
    public void exportTeacherReviewData(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "status", required = false) String status,
            HttpServletResponse response) {
        try {
            // 构建查询条件
            QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();

            if (name != null && !name.trim().isEmpty()) {
                queryWrapper.like("name", name.trim());
            }

            if (status != null && !status.trim().isEmpty()) {
                queryWrapper.eq("certification_status", Integer.parseInt(status.trim()));
            }

            // 查询教师数据
            List<Teachers> teachers = teacherService.list(queryWrapper);

            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("教师审核数据");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {
                "教师姓名", "手机号", "邮箱", "学历", "专业", "毕业院校",
                "教学年限", "申请时间", "审核状态", "拒绝原因"
            };

            // 创建标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 12);
            headerStyle.setFont(headerFont);
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);
            headerStyle.setBorderLeft(BorderStyle.THIN);

            // 设置标题
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 4000); // 设置列宽
            }

            // 创建数据样式
            CellStyle dataStyle = workbook.createCellStyle();
            dataStyle.setBorderBottom(BorderStyle.THIN);
            dataStyle.setBorderTop(BorderStyle.THIN);
            dataStyle.setBorderRight(BorderStyle.THIN);
            dataStyle.setBorderLeft(BorderStyle.THIN);

            // 填充数据
            int rowNum = 1;
            for (Teachers teacher : teachers) {
                // 获取认证信息
                TeacherCertification certification = teacherCertificationService.getOne(
                    new QueryWrapper<TeacherCertification>().eq("teacher_id", teacher.getId())
                );

                Row row = sheet.createRow(rowNum++);

                // 教师姓名
                Cell cell0 = row.createCell(0);
                cell0.setCellValue(teacher.getName() != null ? teacher.getName() : "");
                cell0.setCellStyle(dataStyle);

                // 手机号
                Cell cell1 = row.createCell(1);
                cell1.setCellValue(certification != null && certification.getPhone() != null ? certification.getPhone() : "");
                cell1.setCellStyle(dataStyle);

                // 邮箱
                Cell cell2 = row.createCell(2);
                cell2.setCellValue(certification != null && certification.getEmail() != null ? certification.getEmail() : "");
                cell2.setCellStyle(dataStyle);

                // 学历
                Cell cell3 = row.createCell(3);
                cell3.setCellValue(certification != null && certification.getEducation() != null ? certification.getEducation() : "");
                cell3.setCellStyle(dataStyle);

                // 专业
                Cell cell4 = row.createCell(4);
                cell4.setCellValue(certification != null && certification.getMajor() != null ? certification.getMajor() : "");
                cell4.setCellStyle(dataStyle);

                // 毕业院校
                Cell cell5 = row.createCell(5);
                cell5.setCellValue(certification != null && certification.getGraduateSchool() != null ? certification.getGraduateSchool() : "");
                cell5.setCellStyle(dataStyle);

                // 教学年限
                Cell cell6 = row.createCell(6);
                cell6.setCellValue(teacher.getTeachingAge() != null ? teacher.getTeachingAge().toString() + "年" : "");
                cell6.setCellStyle(dataStyle);

                // 申请时间
                Cell cell7 = row.createCell(7);
                cell7.setCellValue(teacher.getCreatedAt() != null ? teacher.getCreatedAt().toString() : "");
                cell7.setCellStyle(dataStyle);

                // 审核状态
                Cell cell8 = row.createCell(8);
                String statusText = TeacherCertificationStatus.getDescriptionByCode(teacher.getCertificationStatus());
                cell8.setCellValue(statusText);
                cell8.setCellStyle(dataStyle);

                // 拒绝原因
                Cell cell9 = row.createCell(9);
                cell9.setCellValue(certification != null && certification.getRejectReason() != null ? certification.getRejectReason() : "");
                cell9.setCellStyle(dataStyle);
            }

            // 设置响应头
            String fileName = "教师审核数据_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 写入响应
            workbook.write(response.getOutputStream());
            workbook.close();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
